// weather.js  - 完整实现版 
class WeatherWidget {
    constructor() {
        // API基础配置 
        this.API_URL_BASE = 'https://cn.apihz.cn/api/tianqi/tqyb.php?id=&key='; 
        
        // 完整图标映射表 
        this.weatherIconMap  = {
            '晴': {
                icon: 'fa-sun',
                effect: this.animateSun  
            },
            '多云': {
                icon: 'fa-cloud',
                effect: this.animateCloud  
            },
            '阴': {
                icon: 'fa-cloud',
                effect: this.animateCloud  
            },
            '雨': {
                icon: 'fa-cloud-rain',
                effect: this.animateRain  
            },
            '雪': {
                icon: 'fa-snowflake',
                effect: this.animateSnow  
            }
        };
 
        // 完整初始化流程 
        this.init(); 
    }
 
    init() {
        this.cacheElements(); 
        this.initCanvas(); 
        this.getCityAndFetchWeather(); 
    }
 
    cacheElements() {
        this.elements  = {
            loader: document.querySelector('.loader'), 
            content: document.querySelector('.content'), 
            errorOverlay: document.querySelector('.error-overlay'), 
            place: document.getElementById('place'), 
            temperature: document.getElementById('temperature'), 
            windSpeed: document.getElementById('windSpeed'), 
            humidity: document.getElementById('humidity'), 
            updateTime: document.getElementById('updateTime'), 
            weatherIcon: document.getElementById('weatherIcon'), 
            canvas: document.getElementById('weatherCanvas') 
        };
    }
 
    initCanvas() {
        this.ctx  = this.elements.canvas.getContext('2d'); 
        this.elements.canvas.width  = 120;
        this.elements.canvas.height  = 120;
    }
 
    async getCityAndFetchWeather() {
        try {
            const location = await parseTencentLocation();
            // console.log(' 完整定位数据:', location);
            if (!location.province)  {
                throw new Error('无法获取省份信息');
            }
 
            // 地址备用方案 
            const fallbackPlace = location.district  || location.city  || location.province; 
            if (!fallbackPlace) {
                throw new Error('无法获取有效地点信息');
            }
 
            await this.fetchWeather({ 
                province: location.province, 
                place: fallbackPlace,
            });
        } catch (error) {
            console.error(' 定位流程失败:', error);
            this.showError(); 
        }
    }
 
    async fetchWeather(locationInfo) {
        try {
            // 参数处理 
            const processName = (name) => {
                if (!name) return '';
                return name.replace(/[ 省市县区]$/, '').trim();
            };
 
            const params = new URLSearchParams({
                sheng: processName(locationInfo.province), 
                place: processName(locationInfo.place) 
            });
 
            // 调试输出 
            console.log(' 最终请求参数:', params.toString()); 
 
            // 发起请求 
            const response = await fetch(`${this.API_URL_BASE}&${params}`);
            if (!response.ok)  {
                throw new Error(`HTTP错误 ${response.status}`); 
            }
 
            const data = await response.json(); 
            // console.log(' 原始API响应:', data);
 
            if (data.code  !== 200) {
                throw new Error(data.msg  || 'API返回异常状态码');
            }
 
            this.updateDisplay(data); 
            this.showContent(); 
        } catch (error) {
            console.error(' 获取天气失败:', error);
            this.showError(); 
        }
    }
 
	updateDisplay(data) {
	    // 完整数据映射 
	    const displayData = {
	        place: data.place.split(', ').join(' · ') || '未知地区',
	        temperature: data.temperature ? `${data.temperature}` : '--',
	        windSpeed: data.windScale ? `${data.windScale} ` : '--',
	        humidity: data.humidity ? `${data.humidity}%` : '--',
	        updateTime: new Date().toLocaleTimeString(),
	        weather: data.weather1 || '晴'
	    };
	
	    // 设置强类型校验 
	    if (typeof displayData.place !== 'string') {
	        console.warn('异常地点数据:', displayData.place); 
	        displayData.place = '数据异常';
	    }
	
	    // 提取place字段中的特定部分
	    function extractPlaceParts(placeStr) {
	        let parts = placeStr.split(' · ');
	        let firstPart = parts[0];
	        let lastPart = parts[parts.length - 1];
	        return `${firstPart} · ${lastPart}`;
	    }
	
	    // 更新DOM元素 
	    this.elements.place.textContent = extractPlaceParts(displayData.place);
	    this.elements.temperature.textContent = displayData.temperature; 
	    this.elements.windSpeed.textContent = displayData.windSpeed; 
	    this.elements.humidity.textContent = displayData.humidity; 
	    this.elements.updateTime.textContent = ` ${displayData.updateTime}`; 
	    
	    // 新增：更新welcomeMsg div的内容
	    const welcomeMsgElement = document.getElementById('welcomeMsg');
	    if (welcomeMsgElement) {
	        welcomeMsgElement.textContent = `欢迎来自${displayData.place}的朋友访问`;
	    }
	
	    // 图标处理 
	    const weatherConfig = this.weatherIconMap[displayData.weather] || this.weatherIconMap['晴'];
	    this.elements.weatherIcon.className = `fas ${weatherConfig.icon} weather-icon`;
	
	    // 执行动画效果 
	    if (weatherConfig.effect) {
	        weatherConfig.effect.call(this); 
	    }
	}
 
    showContent() {
        this.elements.loader.style.display  = 'none';
        this.elements.content.style.opacity  = '1';
        this.elements.errorOverlay.style.display  = 'none';
    }
 
    showError() {
        this.elements.loader.style.display  = 'none';
        this.elements.errorOverlay.style.display  = 'flex';
    }
 
    animateSun() {
        this.ctx.clearRect(0,  0, 120, 120);
        this.ctx.fillStyle  = 'rgba(255, 204, 0, 0.2)';
        this.ctx.beginPath(); 
        this.ctx.arc(60,  60, 40, 0, Math.PI * 2);
        this.ctx.fill(); 
    }
 
    animateCloud() {
        this.ctx.clearRect(0,  0, 120, 120);
        this.ctx.fillStyle  = 'rgba(221, 221, 221, 0.8)';
        this.ctx.beginPath(); 
        this.ctx.ellipse(40,  50, 25, 20, 0, 0, Math.PI * 2);
        this.ctx.ellipse(60,  60, 30, 25, 0, 0, Math.PI * 2);
        this.ctx.ellipse(80,  55, 25, 20, 0, 0, Math.PI * 2);
        this.ctx.fill(); 
    }
 
    animateRain() {
        this.ctx.clearRect(0,  0, 120, 120);
        this.ctx.strokeStyle  = 'rgba(0, 120, 255, 0.6)';
        this.ctx.lineWidth  = 2;
        for (let i = 0; i < 20; i++) {
            const x = Math.random()  * 120;
            const y = Math.random()  * 120;
            this.ctx.beginPath(); 
            this.ctx.moveTo(x,  y);
            this.ctx.lineTo(x  + 3, y + 10);
            this.ctx.stroke(); 
        }
    }
 
    animateSnow() {
        this.ctx.clearRect(0,  0, 120, 120);
        this.ctx.fillStyle  = 'rgba(255, 255, 255, 0.8)';
        for (let i = 0; i < 30; i++) {
            const x = Math.random()  * 120;
            const y = Math.random()  * 120;
            this.ctx.beginPath(); 
            this.ctx.arc(x,  y, 2, 0, Math.PI * 2);
            this.ctx.fill(); 
        }
    }
}
 
// 腾讯地图定位服务（完整实现）
const TENCENT_MAP_API_KEY = "";
const parseTencentLocation = () => {
    return new Promise((resolve, reject) => {
        const callbackName = 'tencentLocationCallback';
        const timeout = setTimeout(() => {
            reject(new Error('定位请求超时'));
            cleanup();
        }, 8000);
 
        const cleanup = () => {
            clearTimeout(timeout);
            delete window[callbackName];
            script.remove(); 
        };
 
        window[callbackName] = (response) => {
            if (response.status  === 0) {
                const info = response.result.ad_info; 
                resolve({
                    province: info.province, 
                    city: info.city, 
                    district: info.district, 
                    full: info 
                });
            } else {
                reject(new Error(`定位失败: ${response.message}`)); 
            }
            cleanup();
        };
 
        const script = document.createElement('script'); 
        script.src  = `https://apis.map.qq.com/ws/location/v1/ip?key=${TENCENT_MAP_API_KEY}&output=jsonp&callback=${callbackName}`; 
        script.onerror  = () => {
            reject(new Error('无法加载定位脚本'));
            cleanup();
        };
        document.body.appendChild(script); 
    });
};
 
// 初始化入口 
document.addEventListener('DOMContentLoaded',  () => {
    try {
        new WeatherWidget();
    } catch (error) {
        console.error(' 初始化失败:', error);
        document.querySelector('.error-overlay').style.display  = 'flex';
    }
});